/**
 * websocket 封装使用
 * @author Farley
 * @date 2021-06-02
 * @example
 * import { connectWebSocket, disconnectWebSocket } from '@/utils/websocket'
 * export default {
 *   data() {
 *     return {}
 *   },
 *   methods: {},
 *   mounted() {
 *     // 建立 socket 连接及订阅
 *     let socket = connectWebSocket({
 *       url: 'http://192.168.7.124:8080/stomp/websocketJS1',
 *       topic: {
 *         '/topic/satellite': res => {
 *           console.log(res)
 *         },
 *         '/topic/station': res => {
 *           console.log(res)
 *         }
 *       }
 *     })
 *
 *     setTimeout(() => {
 *       // 断开连接
 *       disconnectWebSocket(socket)
 *     }, 5000)
 *   }
 * }
 */

import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

/**
 * 建立 websocket 连接
 * @author Farley
 * @date 2021-06-02
 * @param {any} option.url  连接地址
 * @param {any} option.incoming  心跳传入时间
 * @param {any} option.outgoing  心跳传出时间
 * @param {any} option.timeout  超时连接时长
 * @param {any} option.headers  请求头
 * @returns {any}
 */
export function connectWebSocket(option) {
  let socket = new SockJS(option.url)
  // 获取STOMP子协议的客户端对象
  let stompClient = Stomp.over(socket)
  // 定义客户端的认证信息 headers
  let headers = option.headers || {}

  stompClient.debug = undefined
  // 向服务器发起websocket连接
  stompClient.connect(
    {},
    () => {
      if (option.success && typeof option.success === 'function') {
        option.success()
      }
      // stompClient.send('', { atytopic: 'greetings' }, {
      //   userId: '1',
      //   sceneId: '1'
      // })
      option.topic.forEach(key => {
        stompClient.subscribe(key.name, res => {
          // option.topic[key](res)
          key.callback(res)
        })
      })
      // Object.keys(option.topic).forEach(key => {
      //   stompClient.subscribe(key, res => {
      //     option.topic[key](res)
      //   })
      // })
    },
    err => {
      console.log(err)
    }
  )

  return { socket, stompClient }
}

/**
 * 断开连接
 * @author Farley
 * @date 2021-06-02
 * @returns {any}
 */
export function disconnectWebSocket(stompClient) {
  stompClient.disconnect()
}
